package org.cloud.im.server.command.handler;

import org.cloud.im.core.ImChannelContext;
import org.cloud.im.core.ImPacket;
import org.cloud.im.core.exception.ImException;
import org.cloud.im.core.http.HttpRequest;
import org.cloud.im.core.packets.Command;
import org.cloud.im.core.ws.WsSessionContext;
import org.cloud.im.server.CloudImServerAPI;
import org.cloud.im.server.command.AbstractCmdHandler;
import org.cloud.im.server.processor.handshake.HandshakeCmdProcessor;

import java.util.Objects;

/**
 * @Author: w.weidong.lin@abite.com
 * @Description: 心跳cmd命令处理器
 * @Date: create in 2021/10/19 18:04
 */
public class HandshakeReqHandler extends AbstractCmdHandler {

	@Override
	public ImPacket handler(ImPacket packet, ImChannelContext channelContext) throws ImException {

		HandshakeCmdProcessor handshakeProcessor = this.getMultiProcessor(channelContext,HandshakeCmdProcessor.class);
		if(Objects.isNull(handshakeProcessor)){
			CloudImServerAPI.remove(channelContext, "没有对应的握手协议处理器HandshakeCmdProcessor...");
			return null;
		}
		ImPacket handShakePacket = handshakeProcessor.handshake(packet, channelContext);
		if (handShakePacket == null) {
			CloudImServerAPI.remove(channelContext, "业务层不同意握手");
			return null;
		}
		CloudImServerAPI.send(channelContext, handShakePacket);
		WsSessionContext wsSessionContext = (WsSessionContext) channelContext.getSessionContext();
		HttpRequest request = wsSessionContext.getHandshakeRequestPacket();
		handshakeProcessor.onAfterHandshake(request, channelContext);
		return null;
	}

	@Override
	public Command command() {
		return Command.COMMAND_HANDSHAKE_REQ;
	}
}
